from django.shortcuts import render, redirect
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm, PasswordChangeForm
from django.contrib.auth import login, authenticate, update_session_auth_hash
from django.contrib.auth import logout
from django.contrib.auth.decorators import login_required
from .forms import MyUserCreationForm

# Create your views here.

def register(request):
    if request.method == 'POST':
        form = MyUserCreationForm(request.POST)
        if form.is_valid():
            user = form.save()
            login(request, user)  # 自动登录用户
            return redirect('home')  # 注册成功后重定向到首页
    else:
        form = MyUserCreationForm()
    return render(request, 'user/register.html', {'form': form})

def login_view(request):
    if request.method == 'POST':
        form = AuthenticationForm(data=request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            user = authenticate(request, username=username, password=password)
            if user is not None:
                login(request, user)
                return redirect('home')  # 登录成功后重定向到首页
    else:
        form = AuthenticationForm()
    return render(request, 'user/login.html', {'form': form})

def change_password(request):
    if request.method == 'POST':
        form = PasswordChangeForm(request.user, request.POST)
        if form.is_valid():
            user = form.save()
            update_session_auth_hash(request, user)  # 更新用户会话
            return redirect('home')  # 修改成功后重定向到首页
    else:
        form = PasswordChangeForm(request.user)
    return render(request, 'user/change_password.html', {'form': form})

def logout_view(request):
    logout(request)
    return redirect('home')  # 注销后重定向到首页

@login_required  # 确保用户已登录
def user_management_view(request):
    return render(request, 'user/user_management.html')  # 渲染用户管理页面模板

@login_required
def vip_view(request):
    if request.user.has_perm('user.can_access_vip'):
        return render(request, 'user/vip.html')  # 渲染 VIP 页面模板
    else:
        return redirect('user_management')  # 没有权限则重定向到用户管理页面
